package com.skillworld.webapp.web.pages.rest.user;

import java.util.List;

import org.apache.tapestry5.annotations.ContentType;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;

import com.skillworld.webapp.model.team.Team;
import com.skillworld.webapp.model.userservice.TeamNameAlreadyInUseException;
import com.skillworld.webapp.model.userservice.UserService;
import com.skillworld.webapp.model.util.InvalidArgumentException;
import com.skillworld.webapp.web.util.ErrorMessages;
import com.skillworld.webapp.web.util.Parameter;
import com.skillworld.webapp.web.util.UserSession;

import es.udc.pojo.modelutil.exceptions.InstanceNotFoundException;

@ContentType("text/xml")
public class CreateTeam {

    @SuppressWarnings("unused")
    @Property
    private String errorMessage = null;
    
    @SuppressWarnings("unused")
    @Property
    private long teamId;

    @SessionState(create=false)
    private UserSession userSession;
    
    private boolean userSessionExists;
        
    @Inject
    private UserService userService;

    @Inject
    private Request request;
    
    
    void onPassivate()
    {
        return;
    }
    
    void onActivate()
    {
        if(!userSessionExists)
        {
            errorMessage = ErrorMessages.NOT_LOGGED_IN;
            return;
        }    
        
        String name = request.getParameter("name");
        String info = request.getParameter("info");
        String image = request.getParameter("img");
        String deptsParam = request.getParameter("depts");       

        if (name == null || info == null || image == null || deptsParam == null)        
        { 
            errorMessage = ErrorMessages.INVALID_ARGUMENTS;
            return;
        }       
        
        try 
        { 
            List<Long> deptIds = Parameter.commaSepIds(deptsParam);
            Team newTeam = userService.createTeam(name, info, image, 
                                        this.userSession.getUserId(), 
                                        deptIds);
            teamId = newTeam.getTeamId();
        }
        catch (InstanceNotFoundException e)
        { errorMessage = ErrorMessages.DEPARTMENT_NOT_FOUND; }
        catch (InvalidArgumentException e)
        { errorMessage = ErrorMessages.INVALID_ARGUMENTS; }
        catch (TeamNameAlreadyInUseException e)
        { this.errorMessage = ErrorMessages.NAME_ALREADY_IN_USE; }          
    }    
}
